<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="配置名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入配置名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['agent:management:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['agent:management:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['agent:management:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['agent:management:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="managementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="配置名称" align="center" prop="name" />
      <el-table-column label="配置标识" align="center" prop="key" />
      <el-table-column label="说明" align="center" prop="remark" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['agent:management:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['agent:management:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改配置信息管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- <el-form-item label="租户id" prop="tenantId">
          <el-input v-model="form.tenantId" placeholder="请输入租户id" />
        </el-form-item> -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="12">
            <el-form-item label="配置名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入配置名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配置唯一标识" prop="key">
              <el-input v-model="form.key" placeholder="请输入配置唯一标识" />
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="说明" prop="remark">
          <el-input v-model="form.name" placeholder="请输入配置说明" />
        </el-form-item>
        <!--  -->
        <el-divider>配置内容请谨慎修改</el-divider>
        <div class=" pt20 pb20 pr20"
          style="background: rgb(248, 250, 252);border-radius: 10px;box-shadow: inset 1px 2px 5px rgba(0, 0, 0, 0.05);">

          <!-- 判断内容类型并渲染对应表单 -->
          <el-form-item label="配置内容" prop="value">
            <template v-if="isJsonContent">
              <!-- JSON内容输入 -->
              <div v-for="(value, key) in jsonFields" :key="key">
                <el-form-item :label="formatLabel(key)" :prop="'jsonValues.' + key" :rules="jsonRules[key] || []">
                  <template v-if="typeof value === 'object' && value !== null">
                    <!-- 二级对象属性 -->
                    <div v-for="(subValue, subKey) in value" :key="subKey" style="margin-bottom: 10px;">
                      <image-upload v-if="subKey == 'avatar' || subKey == 'image'" v-model="jsonValues[key][subKey]" :limit="1"/>
                      <!-- 助手KEY不显示 -->
                      <el-input v-else-if="['agent','agentNei'].includes(key) && subKey=='key'" v-model="jsonValues[key][subKey]" :placeholder="'请输入' + subKey"
                        style="width: 90%" v-show="false"/>
                      <el-input v-else v-model="jsonValues[key][subKey]" :placeholder="'请输入' + subKey"
                        style="width: 90%" />
                    </div>
                  </template>
                  <template v-else>
                    <!-- 一级属性 -->
                    <el-input v-model="jsonValues[key]" :placeholder="'请输入' + key" />
                  </template>
                </el-form-item>
                <el-divider></el-divider>

              </div>
            </template>
            <template v-else>
              <!-- 文本内容输入 -->
              <el-input v-model="form.value" type="textarea" placeholder="请输入内容" :rows="4" />
            </template>

            <!-- 内容类型切换按钮 -->
            <!-- <div style="margin-top: 10px;">
              <el-button type="primary" size="mini" @click="toggleContentType">
                {{ isJsonContent ? '切换为文本模式' : '切换为JSON模式' }}
              </el-button>
            </div> -->
          </el-form-item>
        </div>

        <!-- <el-form-item label="更新人" prop="update">
          <el-input v-model="form.update" placeholder="请输入更新人" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listManagement, getManagement, delManagement, addManagement, updateManagement } from "@/api/demo/management";

export default {
  name: "Management",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 配置信息管理表格数据
      managementList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tenantId: null,
        name: null,
        key: null,
        value: null,
        update: null,
      },
      // 表单参数
      form: {},
      // JSON字段定义
      jsonFields: {},
      // JSON值
      jsonValues: {},
      // 是否为JSON内容
      isJsonContent: false,
      // 表单校验
      rules: {
        tenantId: [{ required: true, message: "租户id不能为空", trigger: "blur" }],
        name: [{ required: true, message: "配置名称不能为空", trigger: "blur" }],
        key: [{ required: true, message: "配置唯一key不能为空", trigger: "blur" }]
      },
      // JSON字段验证规则
      jsonRules: {},
      labelData: { agent: '销售助手', agentNei: '内部助手', title: '标题', content: '内容' ,desc:'描述',about:'关于',qrcodeText:'二维码内容',btnText: '按键文案',image:'图片'}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /**
     * 格式化标签显示
     */
    formatLabel(key) {
      // 可以根据需要自定义标签显示格式
      return this.labelData[key]?this.labelData[key]:key;
    },
    /** 查询配置信息管理列表 */
    getList() {
      this.loading = true;
      listManagement(this.queryParams).then(response => {
        this.managementList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tenantId: null,
        name: null,
        key: null,
        value: null,
        createBy: null,
        createTime: null,
        update: null,
        updateTime: null
      };
      this.jsonFields = {};
      this.jsonValues = {};
      this.isJsonContent = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加配置信息管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getManagement(id).then(response => {
        this.form = response.data;
        // 解析配置内容
        this.parseConfigValue(this.form.value);
        this.open = true;
        this.title = "修改配置信息管理";
      });
    },
    /**
     * 解析配置内容，判断是否为JSON格式
     */
    parseConfigValue(value) {
      try {
        const parsed = JSON.parse(value);
        if (typeof parsed === 'object' && parsed !== null) {
          this.isJsonContent = true;
          this.jsonFields = {};
          this.jsonValues = {};

          // 遍历JSON对象，最多支持两级
          for (const key in parsed) {
            if (parsed.hasOwnProperty(key)) {
              this.$set(this.jsonFields, key, parsed[key]);
              if (typeof parsed[key] === 'object' && parsed[key] !== null) {
                // 二级对象
                this.$set(this.jsonValues, key, {});
                for (const subKey in parsed[key]) {
                  if (parsed[key].hasOwnProperty(subKey)) {
                    this.$set(this.jsonValues[key], subKey, parsed[key][subKey]);
                  }
                }
              } else {
                // 一级属性
                this.$set(this.jsonValues, key, parsed[key]);
              }
            }
          }
        } else {
          this.isJsonContent = false;
        }
      } catch (e) {
        // 不是有效的JSON格式
        this.isJsonContent = false;
      }
    },
    /**
     * 切换内容类型
     */
    toggleContentType() {
      if (this.isJsonContent) {
        // 从JSON切换到文本
        this.isJsonContent = false;
        // 将当前JSON值转换为字符串
        const jsonObj = {};
        for (const key in this.jsonFields) {
          if (this.jsonFields.hasOwnProperty(key)) {
            if (typeof this.jsonFields[key] === 'object' && this.jsonFields[key] !== null) {
              jsonObj[key] = {};
              for (const subKey in this.jsonValues[key]) {
                if (this.jsonValues[key].hasOwnProperty(subKey)) {
                  jsonObj[key][subKey] = this.jsonValues[key][subKey];
                }
              }
            } else {
              jsonObj[key] = this.jsonValues[key];
            }
          }
        }
        this.form.value = JSON.stringify(jsonObj, null, 2);
      } else {
        // 从文本切换到JSON
        if (this.form.value) {
          this.parseConfigValue(this.form.value);
        } else {
          this.isJsonContent = true;
          this.jsonFields = {};
          this.jsonValues = {};
        }
      }
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 如果是JSON模式，需要将数据合并回form.value
          if (this.isJsonContent) {
            const jsonObj = {};
            for (const key in this.jsonFields) {
              if (this.jsonFields.hasOwnProperty(key)) {
                if (typeof this.jsonFields[key] === 'object' && this.jsonFields[key] !== null) {
                  jsonObj[key] = {};
                  for (const subKey in this.jsonValues[key]) {
                    if (this.jsonValues[key].hasOwnProperty(subKey)) {
                      jsonObj[key][subKey] = this.jsonValues[key][subKey];
                    }
                  }
                } else {
                  jsonObj[key] = this.jsonValues[key];
                }
              }
            }
            this.form.value = JSON.stringify(jsonObj);
          }

          if (this.form.id != null) {
            updateManagement(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addManagement(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除配置信息管理编号为"' + ids + '"的数据项？').then(function () {
        return delManagement(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('agent/management/export', {
        ...this.queryParams
      }, `management_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
/* 可以添加一些样式优化表单布局 */
</style>